﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using NHibernate;
using NHibernate.Linq;

namespace NMix.NHibernate
{
    public class DbBase<T> where T : class
    {
        protected ISession _session;

        public DbBase()
        {
        }

        public virtual void Save(T entity)
        {
            using (_session = NHibernateHelper.GetCurrentSession())
            {
                using (var tx = _session.BeginTransaction())
                {
                    try
                    {
                        _session.Save(entity);
                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        tx.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public virtual void Delete(T entity)
        {
            using (_session = NHibernateHelper.GetCurrentSession())
            {
                using (var tx = _session.BeginTransaction())
                {
                    try
                    {
                        _session.Delete(entity);
                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        tx.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public virtual void Update(T entity)
        {
            using (_session = NHibernateHelper.GetCurrentSession())
            {
                using (var tx = _session.BeginTransaction())
                {
                    try
                    {
                        _session.Update(entity);
                        tx.Commit();
                    }
                    catch (Exception ex)
                    {
                        tx.Rollback();
                        throw ex;
                    }
                }
            }
        }

        public virtual T FindBy(object id)
        {
            using (_session = NHibernateHelper.GetCurrentSession())
            {
                return _session.Get<T>(id);
            }
        }

        public virtual IList<T> FindBy(Func<T, bool> expression)
        {
            using (_session = NHibernateHelper.GetCurrentSession())
            {
                IList<T> list = _session.Query<T>().Where(expression).ToList();
                return list;
            }
        }

        public virtual IList<T> GetList()
        {
            using (_session = NHibernateHelper.GetCurrentSession())
            {
                IList<T> list = _session.Query<T>().ToList();
                return list;
            }
        }
    }
}
